package curl

import (
	"errors"

	"github.com/sirupsen/logrus"
	"github.com/valyala/fasthttp"
)

/**
 * 发送GET请求
 *
 */
func Get(request Params) (body []byte, err error) {
	httpCode, body, err := Request(Params{
		Url:         request.Url,
		Body:        request.Body,
		Header:      request.Header,
		Method:      "GET",
		ContentType: request.ContentType,
	})
	if err != nil {
		return body, err
	}
	if httpCode != 200 {
		return body, errors.New("http code fail")
	}

	return
}

/**
 * 发送POST请求
 *
 */
func Post(request Params) (body []byte, err error) {
	contentType := "application/json"
	if request.ContentType != "" {
		contentType = request.ContentType
	}
	httpCode, body, err := Request(Params{
		Url:         request.Url,
		Body:        request.Body,
		Header:      request.Header,
		Method:      "POST",
		ContentType: contentType,
	})
	if err != nil {
		return body, err
	}
	if httpCode != 200 {
		return body, errors.New("http code fail")
	}

	return
}

type (
	Params struct {
		Url         string
		Body        string
		Header      map[string]string
		Method      string
		ContentType string
	}
)

/**
 * 发送请求
 *
 */
func Request(params Params) (httpCode int, body []byte, err error) {
	// 请求
	req := fasthttp.AcquireRequest()
	resp := fasthttp.AcquireResponse()
	defer fasthttp.ReleaseRequest(req)
	defer fasthttp.ReleaseResponse(resp)

	req.SetRequestURI(params.Url)

	for key, value := range params.Header {
		req.Header.Set(key, value)
	}

	if params.Method != "" {
		req.Header.SetMethod(params.Method)
	}

	if params.ContentType != "" {
		req.Header.SetContentType(params.ContentType)
	}

	// 设定body体
	if params.Body != "" {
		req.SetBodyString(params.Body)
	}

	if err = fasthttp.Do(req, resp); err != nil {
		logrus.Error("Curl Request err : ", err.Error())
		return
	}

	httpCode = resp.StatusCode()
	if httpCode != fasthttp.StatusOK {
		logrus.Error("Curl Request Status Code : ", httpCode)
	}

	body = resp.Body()
	return
}
